package com.github.uiautomator

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.text.format.Formatter
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.android.permission.FloatWindowManager
import com.github.uiautomator.util.MemoryManager
import com.github.uiautomator.util.Permissons4App
import com.wetest.uia2.Main
import wxpay.WXPayActivity
import java.util.concurrent.Executors

class MainActivity : Activity() {
    private val TAG = "ATXMainActivity"
    private var tvInStorage: TextView? = null
    private var textViewIP: TextView? = null
    private var httpServerState: TextView? = null
    private var tvHttpServerApi: TextView? = null

    private var floatView: FloatView? = null

    @RequiresApi(api = Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context = this

        val btnFinish = findViewById<Button>(R.id.btn_finish)
        btnFinish.setOnClickListener { view: View? ->
            stopService(Intent(this@MainActivity, Service::class.java))
            finish()
        }

        val btnIdentify = findViewById<Button>(R.id.btn_identify)
        btnIdentify.setOnClickListener { v: View? ->
            val intent = Intent(this@MainActivity, IdentifyActivity::class.java)
            val bundle = Bundle()
            bundle.putString("theme", "RED")
            intent.putExtras(bundle)
            startActivity(intent)
        }

        findViewById<View>(R.id.accessibility).setOnClickListener { v: View? -> startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)) }

        findViewById<View>(R.id.development_settings).setOnClickListener { v: View? -> startActivity(Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)) }
        findViewById<View>(R.id.btnRunServer).setOnClickListener { v: View ->
            if (Main.automatorHttpServer == null || !Main.automatorHttpServer.isAlive) {
                showToast("启动http服务")
                Executors.newSingleThreadExecutor().execute(Runnable {
                    try {
                        Main.runServer(9009)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                })

                v.postDelayed(object : Runnable {
                    override fun run() {
                        updateHttpServerState()
                    }
                }, 1000)
            } else {
                showToast("http服务已启动")
            }
        }
        findViewById<View>(R.id.btnCloseServer).setOnClickListener { v: View ->
            showToast("关闭http服务")
            Main.automatorHttpServer.stop()
            v.postDelayed(object : Runnable {
                override fun run() {
                    updateHttpServerState()
                }
            }, 1000)
        }

        findViewById<View>(R.id.btnDump).setOnClickListener { v: View? ->
            Main.automatorServiceImpl.dumpWindowHierarchy(false)
        }

        //微信支付测试
        findViewById<View>(R.id.btnWXPay).setOnClickListener { v: View? ->
            WXPayActivity.start(context)
        }

        httpServerState = findViewById(R.id.httpServerState)
        tvHttpServerApi = findViewById(R.id.tvHttpServerApi)

        val intent = intent
        val isHide = intent.getBooleanExtra("hide", false)
        if (isHide) {
            Log.i(TAG, "launch args hide:true, move to background")
            moveTaskToBack(true)
        }
        textViewIP = findViewById(R.id.ip_address)
        tvInStorage = findViewById(R.id.in_storage)

        val permissions = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_PHONE_NUMBERS,
            Manifest.permission.READ_SMS,
            Manifest.permission.RECEIVE_SMS
        )
        Permissons4App.initPermissions(this, permissions)

        val viewVersion = findViewById<View>(R.id.app_version) as TextView
        viewVersion.text = "version: " + appVersionName
    }

    private val appVersionName: String?
        get() {
            try {
                val packageInfo = packageManager.getPackageInfo(packageName, 0)
                return packageInfo.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                return null
            }
        }

    override fun onStart() {
        super.onStart()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Permissons4App.handleRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    fun requestIgnoreBatteryOptimizations(view: View?) {
        val intent = Intent()
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
        intent.setData(Uri.parse("package:$packageName"))
        startActivityForResult(intent, REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) {
            // Check if the user granted the request or not
            Log.d(TAG, "requestIgnoreBatteryOptimizations resultCode: $resultCode")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (isIgnoringBatteryOptimizations) {
                    // User granted the request
                    showToast("requestIgnoreBatteryOptimizations success")
                } else {
                    showToast("requestIgnoreBatteryOptimizations failure")
                    // User didn't grant the request
                }
            }
        }
    }

    @get:RequiresApi(api = Build.VERSION_CODES.M)
    private val isIgnoringBatteryOptimizations: Boolean
        get() {
            var isIgnoring = false
            val powerManager = getSystemService(POWER_SERVICE) as PowerManager
            if (powerManager != null) {
                isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
            }
            return isIgnoring
        }

    private fun showToast(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    fun showFloatWindow(view: View?) {
        val floatEnabled = FloatWindowManager.getInstance().checkFloatPermission(this@MainActivity)
        if (!floatEnabled) {
            Log.i(TAG, "float permission not checked")
            return
        }
        if (floatView == null) {
            floatView = FloatView(this@MainActivity)
        }
        floatView!!.show()
    }

    fun dismissFloatWindow(view: View?) {
        if (floatView != null) {
            Log.d(TAG, "remove floatView immediate")
            floatView!!.hide()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        tvInStorage!!.text = Formatter.formatFileSize(
            this,
            MemoryManager.getAvailableInternalMemorySize()
        ) + "/" + Formatter.formatFileSize(
            this,
            MemoryManager.getTotalExternalMemorySize()
        )
        checkNetworkAddress(null)

        updateHttpServerState()
    }

    fun updateHttpServerState() {
        if (Main.automatorHttpServer != null) {
            runOnUiThread { httpServerState!!.text = if (Main.automatorHttpServer.isAlive) "已启动" else "已停止" }
        } else {
            runOnUiThread { httpServerState!!.text = "已停止" }
        }
    }

    fun checkNetworkAddress(v: View?) {
        val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        val ip = wifiManager.connectionInfo.ipAddress
        val ipStr =
            (ip and 0xFF).toString() + "." + ((ip shr 8) and 0xFF) + "." + ((ip shr 16) and 0xFF) + "." + ((ip shr 24) and 0xFF)
        textViewIP!!.text = ipStr
        textViewIP!!.setTextColor(Color.BLUE)
    }

    override fun onRestart() {
        super.onRestart()
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }


    override fun onDestroy() {
        super.onDestroy()
        // must unbind service, otherwise it will leak memory
        // connection no need to set it to null
        Log.i(TAG, "unbind service")
    }

    companion object {
        private const val REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = 1001

        lateinit var context: Context
    }
}
